#!/usr/bin/python

from bencoding import *
import random
import hashlib
import string

class TrackerRequest:
    
    tran = Bencoding()
    torrent = None
    infoHash = None
    peerId = None
    port = 0
    uploaded = 0
    downloaded = 0
    amountLeft = 0
    isCompact = True
    noPeerId = True
    event = None
    ip = None
    numWant = 50
    key = None
    trackerId = None

    def __init__(self, torrent = None, connection = None):
        if torrent is None and connection is None:
            pass
        #elif connection is None:
            #raise ArgumentError
        else:
            self.torrent = torrent
            self.infoHash = self.genInfoHash(self.tran.makeBen(self.torrent["info"]))
            self.peerId = self.genPeerId()
            #self.port = connection.port
            #self.uploaded = connection.uploaded
            #self.downloaded = connection.downloaded
            #self.amountLeft = connection.amountLeft
            #if connection is not None and connection.event is not None:
                #self.event = connection.event

    def urlEncode(self, string):
        outStr = ""
        for char in string:
            if ord(char) <= 9:
                tmpChar = hex(ord(char))
                tmpChar = tmpChar[0:2] + '0' + tmpChar[2]
                outStr = outStr + tmpChar
            else:
                tmpChar = hex(ord(char))
                outStr = outStr + tmpChar
        outStr = outStr.replace("0x","%")
        return outStr

    def genInfoHash(self, infoValue):
        shaHash = hashlib.sha1()
        shaHash.update(infoValue)
        info_hash = shaHash.digest()
        return info_hash

    def genTrackerTuple(self):
        trackStr = self.torrent["announce-list"][4][0]
        print trackStr
        left = string.rfind(trackStr, ":")
        right = string.rfind(trackStr, "/")
        address = trackStr[7:left]
        portNum = int(trackStr[left+1:right])
        return (address, portNum)

    def genPeerId(self):
        peerId = "-VT0001-"
        for i in range(12):
            peerId = peerId + str(random.randrange(0,9))
        return peerId

#torFile = file("../Desktop/[isoHunt] Lost.S06E06.HDTV.XviD-2HD.torrent")
#torInfo = torFile.read()
#tran = Bencoding()
#torrent = tran.makeBin(torInfo)
#track = TrackerRequest()

#info_hash = track.genInfoHash(tran.makeBen(torrent["info"]))

#print info_hash, track.genPeerId(), torrent["announce-list"]

    
    
